package com.hpxx.ylzswl.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hpxx.ylzswl.R;
import com.hpxx.ylzswl.adapter.OrderSearchAdapter;
import com.hpxx.ylzswl.base.BaseActivity;
import com.hpxx.ylzswl.bean.OrderListBean;
import com.hpxx.ylzswl.https.HttpAddress;
import com.hpxx.ylzswl.https.RequestParams;
import com.hpxx.ylzswl.info.ManageInfo;
import com.hpxx.ylzswl.views.NoScrollingListView;
import com.universal.frame.generalutils.GeneralUtil;
import com.universal.frame.generalutils.JsonUtil;
import com.universal.frame.generalutils.ToastUtil;
import com.universal.frame.okhttp.OKHttpUtils;
import com.universal.frame.okhttp.ResultCallBack;
import com.universal.frame.pulltorefresh.PullToRefreshBase;
import com.universal.frame.pulltorefresh.PullToRefreshScrollView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Request;

import static com.activeandroid.Cache.getContext;

/**
 * Created by Administrator on 2017/11/10.
 */

public class OrderSearchActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2,View.OnClickListener,ResultCallBack, AdapterView.OnItemClickListener {

    private LinearLayout ll_search,ll_search_isgone;
    private PullToRefreshScrollView pull_refresh_scrollview;
    private NoScrollingListView nsl_list;
    private int pageIndex = 0;
    private boolean toRefresh = true;
    private EditText et_sea_con;

    private List<OrderListBean> list = new ArrayList<OrderListBean>();
    private OrderSearchAdapter adapter;
    private String sn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_order);
        back();
        setTitle("搜索结果");
    }
    private void orderListPost( int pageIndex,String sn){
        OKHttpUtils.postAsync(this
                , HttpAddress.ORDER_LIST_URL
                , new RequestParams(this).getOrderListParams(3, "", pageIndex,sn), this
                ,true,1);
    }
    @Override
    public void initView() {
        ll_search = (LinearLayout) findViewById(R.id.ll_search);
        ll_search_isgone = (LinearLayout) findViewById(R.id.ll_search_isgone);

        et_sea_con = (EditText) findViewById(R.id.et_sea_con);
        et_sea_con.setFilters(new InputFilter[]{emojiFilter});
        pull_refresh_scrollview = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
        nsl_list = (NoScrollingListView) findViewById(R.id.nsl_list);
        ll_search.setOnClickListener(this);
        et_sea_con.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(OrderSearchActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    snPost();
                    return true;
                }
                return false;
            }
        });
        initScrollView();
    }

    public void initScrollView() {
        this.pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setPullLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_pull_label_up));
        pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setRefreshingLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_refreshing_label));
        pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setReleaseLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_release_label));

        pull_refresh_scrollview.setMode(PullToRefreshBase.Mode.BOTH);//both  可以上拉、可以下拉
        pull_refresh_scrollview.setOnRefreshListener(this);
        nsl_list.setOnItemClickListener(this);
        adapter = new OrderSearchAdapter(this,list);
        nsl_list.setAdapter(adapter);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ll_search:
                snPost();
                break;

            default:
                break;
        }
    }
    private void snPost(){
        sn = et_sea_con.getText().toString().trim();
        if (sn.isEmpty()){
            ToastUtil.showToast(this,"请输入关键字");
        }else {
            orderListPost(pageIndex,sn);
        }
    }
    @Override
    public void onSuccess(String response, int flag) {
        int status = JsonUtil.getInt(response, "status", 0);
        try {
            switch (flag) {
                case 1:
                    OrderListDetail(response);
                    break;
            }
        } catch (Exception e) {
            GeneralUtil.tryShow(getContext(), e);
        }
    }

    private void OrderListDetail(String response) {
        Log.e("lzx", "shopDetail: " + response);
        pull_refresh_scrollview.onRefreshComplete();
        int status = JsonUtil.getInt(response, "status", 0);
        if (status == 1){
            String data = JsonUtil.getString(response,"data","");
            ManageInfo info = JSON.parseObject(data, ManageInfo.class);
            Log.i("tag", "size = " + info.orderList.size());
            if (info.orderList != null) {
                if (info.orderList.size() > 0) {
                    ll_search_isgone.setVisibility(View.GONE);
                    pull_refresh_scrollview.setVisibility(View.VISIBLE);
                    if (pageIndex == 0) {
                        list.clear();
                        list.addAll(info.orderList);
                    } else {
                        list.addAll(info.orderList);
                    }
                }else {
                    list.clear();
                    ll_search_isgone.setVisibility(View.VISIBLE);
                    pull_refresh_scrollview.setVisibility(View.GONE);
                }
                adapter.notifyDataSetChanged();
                if(info.orderList.size() < 10){
                    toRefresh = false;
                }else{
                    toRefresh = true;
                }
            }


        }else {
            String msg = JsonUtil.getString(response,"msg","");
            ToastUtil.showToast(getApplicationContext(),msg);
            ll_search_isgone.setVisibility(View.GONE);
            pull_refresh_scrollview.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onFailure(Request request, IOException e, int flag) {
        pull_refresh_scrollview.onRefreshComplete();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(OrderSearchActivity.this, OrderDetailsAvtivity.class);
        intent.putExtra("ORDER_ID",list.get(position).orderId);
        startActivity(intent);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        pageIndex =0;
        orderListPost(pageIndex,sn);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        if(toRefresh){
            pageIndex++;
            orderListPost(pageIndex,sn);
        }else{
            ToastUtil.showToast(getApplicationContext(),"没有更多数据");
            pull_refresh_scrollview.onRefreshComplete();
        }
    }
    InputFilter emojiFilter = new InputFilter() {
        Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {

                return "";
            }
            return null;
        }
    };
}
